/**
 * zmn员工模块-员工列表
 * 文件命名格式：zmn.模块名称.表名称.功能.js
 * @author heguanghua
 * @since 2020/04/23 13:45
 */
let baseUrl;
layui.define(['index', 'form', 'table', 'zmnApp', 'laypage', 'zmnSelect','laydate'], function (exports) {
    let $ = layui.$;
    let form = layui.form;
    let layer = layui.layer;
    let table = layui.table;
    let laypage = layui.laypage;
    let laydate = layui.laydate;
    let zmnApp = layui.zmnApp;
    let zmnSelect = layui.zmnSelect;
    let index;
    baseUrl = zmnApp.SYS_BASE_URL;

    table.init('zmn-table', {
        toolbar: "#zmn-table-tool",
        page: true,
        limit: json.pageSize,
        height: 'full-228',
        done: function () {
            $("div[lay-event='LAYTABLE_EXPORT']").attr('lay-event', 'CUSTOM_EXPORT');
        },
    });
    laypage.render(zmnPage.laypageOptions(json));

    //日期
    laydate.render({elem: "#lastLoginTimeRang", range: true, format: 'yyyy/MM/dd'});
    laydate.render({elem: "#entryTimeRange", range: true, format: 'yyyy/MM/dd'});
    laydate.render({elem: "#becomeFormalTimeRange", range: true, format: 'yyyy/MM/dd'});
    laydate.render({elem: "#contractEndTimeNowRange", range: true, format: 'yyyy/MM/dd'});

    // 部门下拉组件
    let deptTree = function (orgId) {
        if (orgId == null) {
            orgId = 0; // 后端Integer类型接收
        }
        zmnSelect.deleteXmSelect("deptId");
        var objMap = zmnSelect.select({
            'deptId': {
                isRadio: true, //单选标识：true-单选；false-多选
                selectedValues: [json.vo.deptId == null ? '' : json.vo.deptId], //已选中值（用于回显)
                tree: {
                    enable: true,
                    //是否展示三角图标
                    showFolderIcon: true,
                    //非严格模式
                    strict: false,
                },
                propMap: {  //选项参数映射配置
                    name: "deptName",   //显示值
                    value: "deptId"  //选中值
                },
                remote: { //远程获取下拉数据
                    enable: true, //开关：true-开启；false-关闭
                    url: '/common/dept/listDeptTree.action?orgId=' + orgId, //服务url
                },
            }
        });
        objMap['deptId'].update({
            filterable: false,
            autoRow: false,
            model: {label: {type: 'text'}},
            on: function (data) {
                if (data.isAdd) {
                    return data.change.slice(0, 1)
                }
            }
        })
    }

    // 组织架构
    zmnSelect.selectlOrganizes(
        {
            platSelectId: 'plat', //平台ID
            orgTwoSelectId: 'orgTwoId', //大区ID
            orgThrSelectId: 'orgId', //子公司ID
        },
        {
            platSelectId: {
                selectedValues: json.plat,
                events: {
                    changed: function (values) {
                        if(zmnUtil.isNotEmptyNull(values)){
                            deptTree(values);
                        }
                    }
                }
            },
            orgTwoSelectId: {
                selectedValues: json.orgTwoId,
                events: {
                    changed: function (values) {
                        if(zmnUtil.isNotEmptyNull(values)){
                            deptTree(values);
                        }
                    }
                }
            },
            orgThrSelectId: {
                isRadio: true,
                selectedValues: json.orgId,
                events: {
                    changed: function (values) {
                        if(zmnUtil.isNotEmptyNull(values)){
                            deptTree(values);
                        }
                    }
                }
            }
        }
    );

    // 加载部门组件 回显部门数据
    if (appUtil.notNull(json.orgId)) {
        deptTree(json.orgId);
    } else if (appUtil.notNull(json.orgTwoId)) {
        deptTree(json.orgTwoId);
    } else {
        deptTree(json.plat);
    }

    let table_ids;
    // 启用/停用（批量）
    table.on("toolbar(zmn-table)", function (obj) {
        let ids = zmnPage.layTabldIds(obj, "staffId");
        table_ids = ids.join(",");
        if (obj.event != "start" && obj.event != "stop" && obj.event != 'resetPwd' && obj.event != 'CUSTOM_EXPORT' && obj.event != 'batchLimitIp') {
            return;
        }


        if (obj.event == 'CUSTOM_EXPORT') {
            $("#query-export").click();
            return;
        }

        if (ids.length === 0) {
            return layer.alert("请选择至少一个要操作的员工！");
        }
        if (obj.event == "resetPwd") {
            zmnPage.ajaxSimple(zmnApp.SYS_BASE_URL + "/staff/modify/resetPwd.action", {id: ids.join(",")}, 2500);
            return;
        }

        if (obj.event == "start" || obj.event == "stop") {
            zmnPage.layStartStopBatch(obj, "/staff/modify/modifyStatus.action", ids.join(","));
            return;
        }

        if (obj.event == "batchLimitIp") {
            batchLimitIp(ids.join(","));
            return;
        }
    });

    let dateRange = null;
        //日期
    laydate.render({
        elem: "#dateRange",
        type: "datetime",
        range: true,
        format: 'yyyy/MM/dd HH:mm:ss',
        zIndex: 99999999,
        value: dateRange,
        done: function (value, startDate, endDate) { //监听日期被切换
            var hours = endDate.hours;
            var minutes = endDate.minutes;
            var seconds = endDate.seconds;
            if (hours == "0" && minutes == "0" && seconds == "0"){
                $(".layui-laydate-footer [lay-type='datetime'].laydate-btns-time").click();
                // 改变结束时间为23:59:59
                $(".laydate-main-list-1 .layui-laydate-content li ol li:last-child").click();
                $(".layui-laydate-footer [lay-type='date'].laydate-btns-time").click();
            }
        }
    });

    // 监听导出事件
    form.on('submit(query-export)', function (data) {
        var params = Object.keys(data.field).map(function (key) {
            return encodeURIComponent(key) + "=" + encodeURIComponent(data.field[key]);
        }).join("&");
        var url = "/staff/exportExcel.action?" + params;

        var judgeUrl = "/staff/judgeExportExcel.action";

        $.ajax({
            async: false,
            type: "POST", url: judgeUrl,
            contentType: "application/json", dataType: "json",
            beforeSend: function () {
                index = layer.load(1, {
                    shade: [0.5, '#DBDBDB']
                });
            },
            success: function (json) {
                layer.close(index);
                if (json.status == 200) {
                    window.open(url, "_parent");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
            },
            complete: function () {
                layer.close(index);
            }
        })

        return false;
    });

    // 启用/停用（单个）
    form.on('switch(chk_status)', function (obj) {
        zmnPage.layStartStop(obj, zmnApp.SYS_BASE_URL + "/staff/modify/modifyStatus.action");
    });

    // 修改排序
    table.on("edit(zmn-table)", function (obj) {
        zmnPage.laySort(obj, zmnApp.SYS_BASE_URL + "/staff/modify/modifySort.action", obj.data.staffId);
    });

    // 选中（单个）
    table.on('tool(zmn-table)', function (obj) {
        var roleId = obj.data.roleId;
        if (obj.event === 'add') {
            if (zmnUtil.isEmptyNull(json.callbackUrl)) {
                return false;
            }
            if (!zmnUtil.isNotZeroInteger(roleId)) {
                return parent.layer.alert("请选择或指定角色");
            }
            var params = {"keyId": json.keyId, "roleIds": roleId}
            callback(json.callbackUrl, params);
            return false;
        }
    });

    $("[id^=operate-]").click(function () {
        let staffId = this.id.split('-')[1];
        let staffStatus = this.id.split('-')[2];
        let type = this.id.split('-')[3];
        let html = "<div class='layui-btn-container'>" +
            "" + (json.hasDetail ? "<a lay-href='" + zmnApp.SYS_BASE_URL + "/staff/detail.action?staffId=" + staffId + "' class='layui-btn layui-btn-sm layui-btn-normal' lay-text='员工信息' style='width:75px'>详情</a>" : '') +
            // "" + (json.hasStaffChange ? "<a lay-href='"+zmnApp.SYS_BASE_URL +"/staff/staffchangelog/list.action?staffId=" + staffId + "'><button class='layui-btn layui-btn-sm layui-btn-normal' style='width:75px'>异动记录</button></a>" : '') +
            "" + (json.hasLeave && (type == 3 || type == 6 || type == 8) && staffStatus < 3 ? "<button onclick='toLeave(" + staffId + ")' class='layui-btn layui-btn-sm layui-btn-normal' style='width:75px'>离职</button>" : '') +
            "" + (json.hasReinstatement && (type == 3 || type == 6 || type == 8) && staffStatus == 3 ? "<button onclick='reinstatement(" + staffId + ")' class='layui-btn layui-btn-sm layui-btn-normal' style='width:75px'>复职</button>" : '') +
            "" + (json.hasBindMaster && (type == 3 || type == 6 || type == 8) ? "<button onclick='bindMaster(" + staffId + ")' class='layui-btn layui-btn-sm layui-btn-normal' style='width:75px'>绑定账户</button>" : '') +
            "" + (json.hasSynchroDingTalk ? "<button onclick='toSetDingTalkId(" + staffId + ")' class='layui-btn layui-btn-sm layui-btn-normal' style='width:75px'>绑定钉钉</button>" : '') +
            "" + (json.hasSynchroBeisen ? "<button onclick='toSetBeisenId(" + staffId + ")' class='layui-btn layui-btn-sm layui-btn-normal' style='width:75px'>绑定北森</button>" : '') +
            "" + (json.hasTempPwd ? "<button onclick='setTempPwd(" + staffId + ")' class='layui-btn layui-btn-sm layui-btn-normal' style='width:75px'>临时密码</button>" : '') +
            "" + (json.hasIpTime ? "<button onclick='setOpenDate(" + staffId + ")' class='layui-btn layui-btn-sm layui-btn-normal' style='width:75px'>不限IP日期</button>" : '') +
            "" + (json.hasWhitelist ? "<button onclick='setWhitelist(" + staffId + ")' class='layui-btn layui-btn-sm layui-btn-normal' style='width:75px'>IP白名单</button>" : '') +
            "" + (json.hasPermitRole ? "<a lay-href='" + zmnApp.SYS_BASE_URL + "/staff/role/list.action?staffId=" + staffId + "' class='layui-btn layui-btn-sm layui-btn-normal' lay-text='角色授权' style='width:75px'>角色授权</a>" : '') +
            "" + (json.hasPermitData ? "<a lay-href='" + zmnApp.SYS_BASE_URL + "/staff/dpermit/organize/tree.action?staffId=" + staffId + "' class='layui-btn layui-btn-sm layui-btn-normal' lay-text='数据授权' style='width:75px'>数据授权</a>" : '') +
            "" + (json.hasEditSubarea ? "<button onclick='toBindSubArea(" + staffId + ")' class='layui-btn layui-btn-sm layui-btn-normal' style='width:75px'>绑定片区</button>" : '') +
            "</div>";
        indexTips = layer.tips(html, this, {
            shade: [0],
            shadeClose: true,
            area: ['300px', '170px'],
            time: 0, //20秒后自动关闭
            tips: [3, '#FFFFFF'],
        });
    });

    staffUtil = {}
    /**
     * 设置临时密码
     */
    setTempPwd = function (staffId) {
        layer.open({
            type: 1,
            title: "临时密码",
            area: '550px',
            content: $('#tmpPwd'),
            btn: ['保存'],
            yes: function (index, layero) {
                console.log(123);
                var pwd = $("#pwd").val();
                if (!pwd) {
                    layer.msg('临时密码不能为空', {icon: 2, time: 1000});
                    return;
                }
                $.ajax({
                    async: false,
                    type: "POST",
                    url: zmnApp.SYS_BASE_URL + "/staff/modify/setTempPwd.action",
                    dataType: "json",
                    data: {"staffId": staffId, "password": pwd},
                    contentType: "application/x-www-form-urlencoded",
                    success: function (json) {
                        if (json.status == 200) {
                            layer.msg(json.message, {icon: 1, time: 1000});
                            $("#location").val(json.data);
                            $(".layui-layer-btn0").css("display", "none");
                            $("#pwdSet").css("display", "none");
                            $("#pwdLogin").css("display", "block");
                        } else {
                            layer.msg(json.message, {icon: 2, time: 1000});
                        }
                        return false;
                    }
                });
            },
            cancel: function (index, layero) {
                $("#location").val("");
                $("#pwd").val("");
                $(".layui-layer-btn0").css("display", "block");
                $("#pwdSet").css("display", "block");
                $("#pwdLogin").css("display", "none");
            }
        })
    }

    /**
     * 设置不限IP日期
     */
    setOpenDate = function (staffId) {
        layer.open({
            type: 2,
            area: ['680px', '490px'],
            fixed: false,
            maxmin: true,
            title: '设置不限IP日期',
            content: zmnApp.SYS_BASE_URL + '/staff/detail/opendate.action?staffId=' + staffId
        });
    }

    /**
     * 设置IP白名单
     */
    setWhitelist = function (staffId) {
        layer.open({
            type: 2,
            area: ['500px', '270px'],
            fixed: false,
            maxmin: true,
            title: '设置IP白名单',
            content: zmnApp.SYS_BASE_URL + '/staff/detail/whitelist.action?staffId=' + staffId
        });
    }

    /**
     * 绑定工程师
     */
    bindMaster = function (staffId) {
        layer.open({
            type: 2,
            area: ['440px', '325px'],
            fixed: false,
            maxmin: true,
            title: "绑定账户",
            shade: 0.8,
            closeBtn: 1,
            content: zmnApp.SYS_BASE_URL + "/staff/bind/master.action?staffId=" + staffId
        });
    }

    /**
     * 绑定片区
     */
     toBindSubArea = function (staffId) {
         layer.open({
             type: 2,
             area: ['560px', '365px'],
             fixed: false,
             maxmin: true,
             title: "绑定片区",
             shade: 0.8,
             closeBtn: 1,
             content: zmnApp.SYS_BASE_URL + "/staff/subarea/addEditView.action?staffId=" + staffId
         });

            // layer.open({
            //     type: 1,
            //     title: "绑定片区",
            //     area: '550px',
            //     content: $('#bindSubArea'),
            //     btn: ['保存','取消'],
            //     yes: function (index, layero) {
            //         console.log(123);
            //         var pwd = $("#pwd").val();
            //         if (!pwd) {
            //             layer.msg('临时密码不能为空', {icon: 2, time: 1000});
            //             return;
            //         }
            //         $.ajax({
            //             async: false,
            //             type: "POST",
            //             url: zmnApp.SYS_BASE_URL + "/staff/modify/setTempPwd.action",
            //             dataType: "json",
            //             data: {"staffId": staffId, "password": pwd},
            //             contentType: "application/x-www-form-urlencoded",
            //             success: function (json) {
            //                 if (json.status == 200) {
            //                     layer.msg(json.message, {icon: 1, time: 1000});
            //                     $("#location").val(json.data);
            //                     $(".layui-layer-btn0").css("display", "none");
            //                     $("#pwdSet").css("display", "none");
            //                     $("#pwdLogin").css("display", "block");
            //                 } else {
            //                     layer.msg(json.message, {icon: 2, time: 1000});
            //                 }
            //                 return false;
            //             }
            //         });
            //     },
            //     cancel: function (index, layero) {
            //         $("#location").val("");
            //         $("#pwd").val("");
            //         $(".layui-layer-btn0").css("display", "block");
            //         $("#pwdSet").css("display", "block");
            //         $("#pwdLogin").css("display", "none");
            //     }
            // })
        }

        layer.ready(function(){
            if(json.status){
                $("#status").val(json.status);
                form.render();
            }
        });

        //批量修改IP日期重置
        form.on('submit(zmn-ip-form-reset)', function (obj) {
            $("#dateRange").val("");
            return false;
        });

        //批量修改IP日期重置
        form.on('submit(zmn-ip-form-submit)', function (obj) {
            var dateRange = $("#dateRange").val();
            var ids = table_ids;
            $.ajax({
                    async: false,
                    type: "POST",
                    url: zmnApp.SYS_BASE_URL + "/staff/modify/batch/opendate.action",
                    dataType: "json",
                    data: {"dateRange": dateRange, "ids": ids},
                    contentType: "application/x-www-form-urlencoded",
                    success: function (json) {
                        if (json.status == 200) {
                            layer.msg('修改成功！', {icon: 1, time: 1000});
                            setTimeout(function () {
                                window.location.reload();
                            }, 1500)
                        } else {
                            layer.msg(json.message, {icon: 2, time: 1000});
                        }
                        return false;
                    }
            });
            return false;
        });
        //对外暴露的接口
        exports('staff_list', {});
    });

function synchroDingTalk(staffId) {
    layui.$.ajax({
        type: "GET", url: baseUrl + '/staff/dingtalk/synchro.action',
        dataType: "json", data: {staffId: staffId},
        success: function (result) {
            console.log(result);
            if (result.status == 200) {
                layui.layer.msg(result.message);
                return false;
            }

            if (result.status == 121701) {
                layui.layer.msg("员工异常，请联系管理员【121701】");
                return false;
            }

            if (result.status == 121702) {
                toSetDingTalkId(staffId);
                return false;
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            layui.layer.alert("系统异常");
        }
    });
}

function toSetDingTalkId(staffId) {
    zmnLayUtil.openIframeCustom(layui.layer, baseUrl + "/staff/dingtalk/toSetDingTalkId.action?staffId=" + staffId, {
        area: ['500px', '300px'],
        title: "绑定钉钉",
        shade: 0.8
    });
}

function toSetBeisenId(staffId) {
    zmnLayUtil.openIframeCustom(layui.layer, baseUrl + "/staff/beisen/toSetBeisenId.action?staffId=" + staffId, {
        area: ['500px', '300px'],
        title: "绑定北森",
        shade: 0.8
    });
}

function toLeave(staffId) {
    zmnLayUtil.openIframeCustom(layui.layer, baseUrl + "/staff/staffleaveoffice/leave.action?staffId=" + staffId, {
        area: ['950px', '620px'],
        title: "离职",
        shade: 0.8
    });
}

function reinstatement(staffId) {
    zmnLayUtil.openIframeCustom(layui.layer, baseUrl + "/staff/staffreinstatement/addEditView.action?staffId=" + staffId, {
        area: ['610px', '400px'],
        title: "复职",
        shade: 0.8
    });
}

// 同步人事系统
function syncBeisengData() {
    layui.$.ajax({
        type: "POST",
        url: baseUrl + '/staff/modify/syncBeisengData.action',
        success: function (result) {
            console.log(result);
            if (result.status == 200) {
                layui.layer.msg("开始同步人事系统");
                return false;
            } else {
                layui.layer.msg(result.message);
                return false;
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            layui.layer.alert("系统异常");
        }
    });
}

    /**
     * 设置不限IP日期
     */
       batchLimitIp = function (staffId) {
           layer.open({
               type: 1,
               title: "设置不限IP日期",
               area: '550px',
               content: $('#batchOpenDate'),
               btn: [],
               yes: function (index, layero) {
               },
               cancel: function (index, layero) {
                   $("#dateRange").val("");
               }
           })
       }


function importStaffPerformance() {
    zmnLayUtil.openIframeCustom(layer, baseUrl + "/staff/toimportperformanceexcel.action", {
        title: "导入员工绩效",
        shade: 0.8,
        area: ["450px", "180px"]
    });
}

function reload(msg) {
    parent.layui.layer.msg(msg, {"icon": 1});
    window.location.reload();
}
